import {
	formatDateTime
} from "@/common/util.js";

if (process.env.NODE_ENV === 'development') {
	console.log('开发环境');
} else {
	console.log('生产环境');
}
const isDev = process.env.NODE_ENV === 'development'

function getPaltFrom() {
	let paltForm = "";
	// #ifdef APP-PLUS
	paltForm = "App"
	// #endif

	// #ifdef H5
	paltForm = "H5"
	// #endif

	// #ifdef MP-WEIXIN
	paltForm = "微信小程序"
	// #endif

	// #ifdef MP-TOUTIAO
	paltForm = "字节跳动小程序"
	// #endif

	// #ifdef MP-ALIPAY
	paltForm = "支付宝小程序"
	// #endif
	return paltForm
}

function getSystemInfo() {
	const sysInfo = uni.getSystemInfoSync();
	delete sysInfo.safeArea
	delete sysInfo.safeAreaInsets
	delete sysInfo.windowWidth
	delete sysInfo.windowHeight
	delete sysInfo.windowTop
	delete sysInfo.windowBottom
	return sysInfo
}

function isWechat() {
	try {
		var ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == 'micromessenger') {
			return true;
		} else {
			return false;
		}
	} catch (e) {
		console.error(e)
		return false
	}
}
// 获取客户端信息
function getClientInfo() {
	let isOnWechat = isWechat()
	let paltForm = getPaltFrom()
	let systemInfo = getSystemInfo()
	let visitTime = formatDateTime(new Date())
	let visitTimes = [visitTime]
	return {
		paltForm,
		systemInfo,
		visitTimes,
		isOnWechat
	}
}

// 添加访客信息统一方法
function addVistorInfo() {
	if (isDev)
		return
	let visitorId = uni.getStorageSync("visitorId")
	console.log("=========================addVistorInfo=========================", visitorId)
	if (visitorId) {
		updateVisitTime(visitorId)
	} else {
		configVistorInfo()
	}
}

// 更新访问时间
function updateVisitTime() {
	let docId = uni.getStorageSync("visitorId")
	let visitTime = formatDateTime(new Date())
	console.log("updateVisitTime=========================", visitTime)
	uniCloud.callFunction({
		name: 'database',
		data: {
			collection: "visitor",
			type: "update-push",
			docId,
			updateKey: "visitTimes",
			updateValue: visitTime
		}
	}).then(res => {
		console.log("updateVisitTime", res)
	})
}

// 第一次配置VistorInfo数据
function configVistorInfo() {
	let clientInfo = getClientInfo()
	uniCloud.callFunction({
		name: 'database',
		data: {
			collection: 'visitor',
			type: "add",
			add: clientInfo
		}
	}).then(res => {
		// debugger
		let result = res.result
		console.log(result.id)
		uni.setStorageSync('visitorId', result.id)
	})
}

// 更新VistorInfo数据
function updateVistorInfo(update) {
	if (isDev)
		return
	let docId = uni.getStorageSync("visitorId")
	uniCloud.callFunction({
		name: 'database',
		data: {
			collection: "visitor",
			type: "update",
			docId,
			update
		}
	}).then(res => {
		console.log("updateVistorInfo", res)
	})
}

module.exports = {
	getPaltFrom,
	addVistorInfo,
	updateVistorInfo,
}
